package com.itogis.interceptors.autoWebEvent;

import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/*
 * web.all.src.js 是抓取页面所有<a></a> 链接点击事件,只要页面应用此js即抓取,当前这个Servlet是记录抓取点击事件的 一般用户网站数据抓取
 */
public class WebStatisticsServlet2 extends AbstractSpringContextServlet {
	private static final long serialVersionUID = 8907626450163952267L;
	// URL parameter names
	private static final String URL_ARGS_DOCUMENT_CHARSET = "charset";
	private static final String URL_ARGS_POST_TYPE = "type";
	// XML constants
	private static final String XML_KEY_DOCUMENT_CHARSET = "documentCharset";
	private Logger log = Logger.getLogger(WebStatisticsServlet2.class);
	private static enum PostType {
		XML, FORM, URL;
		public static PostType getByName(String name)
				throws Exception {
			PostType type = PostType.valueOf(name.toUpperCase());
			if (null == type) {
				throw new Exception( "POST类型不正确: "
								+ name);
			}
			return type;
		}
	};

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {		
		log.info("charset in request= " + request.getCharacterEncoding());
		String charset = request.getParameter(URL_ARGS_DOCUMENT_CHARSET);
		log.info("charset in url=" + charset);
		Writer out = response.getWriter();
		try {
			WebStatistics2 stat = this.parseStatisticsMessage(request);
			log.info("client=" + request.getRemoteAddr() + ":"
					+ request.getRemotePort() + ":\n" + stat.toString());
			System.out.println("client=" + request.getRemoteAddr() + ":"
					+ request.getRemotePort() + ":\n" + new String(stat.toString().getBytes("ISO8859_1"),charset));
			//this.getSpStatisticsService().save(stat);
			// 写回处理结果
			out.write("0 - OK.");
			out.flush();
		} catch (Exception e) {
			log.error("保存用户访问SP网站信息失败", e);
			out.write("1 - ERROR.");
			out.flush();
		}
	}

	private WebStatistics2 parseStatisticsMessage(HttpServletRequest request)
			throws Exception, IOException {
		String postTypeName = request.getParameter(URL_ARGS_POST_TYPE);
		log.info("PostTypeName=" + postTypeName);
		PostType postType = PostType.getByName(postTypeName);

		WebStatistics2 ss = null;
		switch (postType) {
		case XML:
			ss = this.parseStatisticsFromXml(request);
			break;
		case FORM:
			ss = this.parseStatisticsFromForm(request);
			break;
		case URL:
			ss = this.parseStatisticsFromUrl(request);
			break;
		}
		return ss;
	}

	protected String parseUserId(HttpServletRequest request,
			String userTokenValue) {
		String userId = null;
//		UserToken userToken = null;
//		try {
//			// 尝试使用HttpServlet从请求消息中解析UserToken，以此获取UserID
//			userToken = this.parseUserToken(request);
//			log.info("从HTTP请求中解析 UserToken=" + userToken);
//			if (null == userToken && null != userTokenValue) {
//				// 如果失败，就从用客户端发送过来的xml消息中解析UserToken
//				log.info("从XML消息中解析UserToken: " + userTokenValue);
//				String[] tmp = userTokenValue.split(":");
//				if (tmp.length > 2) {
//					String centerKey = this.getCommonService()
//							.getVnetKeyBySecretId(tmp[1]);
//					userToken = new UserToken();
//					userToken.decrypt(tmp[2], centerKey);
//				}
//			}
//			if (null != userToken) {
//				userId = userToken.getUserID();
//			}
//		} catch (Exception e) {
//			log.warn("解析UserToken失败", e);
//		}
		log.info("解析结果： UserID=" + userId);
		return userId;
	}

	private WebStatistics2 parseStatisticsFromXml(HttpServletRequest request)
			throws Exception, IOException {
		Document doc = this.parseRequestXml(request);
		if (true == log.isDebugEnabled()) {
			StringWriter sw = new StringWriter();
			OutputFormat of = OutputFormat.createPrettyPrint();
			XMLWriter out = new XMLWriter(sw, of);
			out.write(doc);
			out.flush();
			String xml = sw.toString();
			log.debug("xml payload:\n" + xml);
		}
		String documentCharset = doc.getRootElement().attributeValue(
				XML_KEY_DOCUMENT_CHARSET);
		log.info("documentCharset=" + documentCharset);
		// 从XML消息中提取数据
		WebStatistics2 stat = WebStatistics2.parseFromXml(doc);
		String userId = this.parseUserId(request, stat.getUserId());
		stat.setUserId(userId);
		return stat;
	}

	private WebStatistics2 parseStatisticsFromUrl(HttpServletRequest request)
			throws UnsupportedEncodingException {
		WebStatistics2 ss = WebStatistics2.parseFromUrl(request);
		ss.setUserId(this.parseUserId(request, null));
		return ss;
	}

	private WebStatistics2 parseStatisticsFromForm(HttpServletRequest request)
			throws Exception, UnsupportedEncodingException {
		WebStatistics2 ss = WebStatistics2.parseFromForm(request);
		ss.setUserId(this.parseUserId(request, null));
		return ss;
	}
}
